package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Role;
import com.itheima.health.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("role")
public class RoleController {

    @DubboReference
    private RoleService roleService;

    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @RequestMapping("all")
    public Result findAll(){
        List<Role> roleList = roleService.findAll();
        if (roleList==null){
            return new Result(false, MessageConst.QUERY_ROLE_FAIL);
        }
        return new Result(true,MessageConst.QUERY_ROLE_SUCCESS,roleList);
    }

    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @GetMapping("findPage")
    public Result findPage(QueryPageBean queryPageBean){
        PageResult pageResult = roleService.findPage(queryPageBean);
        if (pageResult==null){
            return new Result(false,MessageConst.QUERY_ROLE_FAIL);
        }
        return new Result(true,MessageConst.QUERY_ROLE_SUCCESS,pageResult);
    }

    @PreAuthorize("hasAuthority('ROLE_ADD')")
    @PostMapping("add")
    public Result add(@RequestBody Role role, @RequestParam("permissionIds") Integer[] pIds){
        boolean flag = roleService.add(role,pIds);
        if (!flag){
            return new Result(false,MessageConst.ADD_ROLE_FAIL);
        }
        return new Result(true,MessageConst.ADD_ROLE_SUCCESS);
    }

    @PreAuthorize("hasAuthority('ROLE_QUERY')")
    @GetMapping("findById")
    public Result findById(Integer id){
        Role role = roleService.findById(id);
        if (role == null){
            return new Result(false,MessageConst.QUERY_ROLE_FAIL);
        }
        return new Result(true,MessageConst.QUERY_ROLE_SUCCESS,role);
    }


    @PreAuthorize("hasAuthority('ROLE_EDIT')")
    @PostMapping("update")
    public Result update(@RequestBody Role role,@RequestParam("permissionIds")Integer[] pIds){
        boolean flag = roleService.update(role,pIds);
        if (!flag){
            return new Result(false,MessageConst.EDIT_USER_FAIL);
        }
        return new Result(true,MessageConst.EDIT_USER_SUCCESS);
    }


    @PreAuthorize("hasAuthority('ROLE_DELETE')")
    @GetMapping("delete")
    public Result deleteById(Integer id){

        boolean flag = roleService.deleteById(id);
        if (!flag){
            return new Result(false,MessageConst.DELETE_ROLE_FAIL);
        }
        return new Result(true,MessageConst.DELETE_ROLE_SUCCESS);

    }


}
